<template>
  <div class="layout-padding">
    <el-tabs v-model="activeName">
      <div class="layout-padding-auto layout-padding-view">
        <el-row class="ml10" v-show="showSearch">
          <el-form :inline="true" :model="state.queryForm" ref="queryRef">
            <el-form-item label="日期" prop="infusionDate" >
              <el-date-picker v-model="state.queryForm.infusionDate" type="date" placeholder="选择日期"
                 :clearable="false" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%"/>
            </el-form-item>
            <el-form-item>
              <el-button @click="getAllList" formDialogRef icon="search" type="primary">
                {{ $t('common.queryBtn') }}
              </el-button>
              <el-button @click="resetQuery" formDialogRef icon="Refresh">{{ $t('common.resetBtn') }} </el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <el-row>
          <div class="mb8" style="width: 100%">
            <el-button CoreDialog icon="folder-add" type="primary" class="ml10" @click="onOpenCoreDialogRef('add')">
              {{ $t('common.addBtn') }}
            </el-button>
          </div>
        </el-row>
        <el-tab-pane label="座位模式" name="first">
          <splitpanes>
            <pane class="ml10">
              <splitpanes>
                <pane size="300">
                  <div class="layout-padding-auto layout-padding-view">
                    <div class="p-4 min-w-[375px] md:min-w-[700px] xl:min-w-[800px] mt-3 grid grid-cols-1 gap-3
                md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 3xl:grid-cols-8" style="max-height: 600px;overflow-y: auto;">
                      <CountDown v-for="(item, index) in otherState.seats" :key="index" :seat="item"
                        @openSeatDialog="onOpenChangeSeatDialogRef" @openEditDialog="onOpenCoreDialogRef"/>
                    </div>
                  </div>
                </pane>
                <pane class="ml8">
                  <div class="layout-padding-auto layout-padding-view" style="max-height: 640px">
                    <el-table :data="otherState.toBeInfused" row-key="coreId" >
                      <el-table-column label="居民姓名" fixed prop="name" show-overflow-tooltip />
                      <el-table-column label="开始时间" fixed prop="yjkssj" show-overflow-tooltip />
                      <el-table-column label="结束时间" fixed prop="yjjssj" show-overflow-tooltip />
                      <el-table-column fixed="right" label="操作" width="120">
                        <template #default="scope">
                          <el-button type="primary" link size="small"
                              @click.native.prevent="onOpenChangeSeatDialogRef({type: 'start',coreId: scope.row.coreId,seatId: scope.row.seatId})"
                              v-show="checkDate(scope.row.infusionDate)" >开始输液</el-button>
                          <el-button type="primary" link
                              v-show="checkEditDate(scope.row.infusionDate)"
                              @click="onOpenCoreDialogRef('edit',scope.row.coreId)">编辑</el-button>
                        </template>
                        </el-table-column>
                    </el-table>
                  </div>
                </pane>
              </splitpanes>
            </pane>
          </splitpanes>
        </el-tab-pane>
        <el-tab-pane label="列表模式" name="second" style="height: 635px;overflow-y: auto;">
          <div>
            <span>
            今日输液总量：{{ statistics['totalInfusion'] }}ml，已输液：{{ statistics['finishInfusion'] }}ml，
            总袋数：{{ statistics['totalInfusionBag'] }}，已输液袋数：{{ statistics['finishInfusionBag'] }}
            </span>
          </div>
          <el-table :data="state.dataList" row-key="index" style="width: 100%;text-align: center" border
                    :header-cell-style="tableStyle.headerCellStyle" :row-class-name="tableRowClassName"
                    :cell-style="tableStyle.cellStyle">
            <el-table-column label="居民姓名" prop="name" show-overflow-tooltip />
            <el-table-column label="总输液量" prop="totalInfusion" show-overflow-tooltip />
            <el-table-column label="总袋数" prop="totalInfusionBag" show-overflow-tooltip />
            <el-table-column label="输液时长" prop="syyjsc" show-overflow-tooltip />
            <el-table-column label="预计开始时间" prop="yjkssj" show-overflow-tooltip />
            <el-table-column label="预计结束时间" prop="yjjssj" show-overflow-tooltip />
            <el-table-column label="操作" show-overflow-tooltip >
              <template #default="scope">
                <el-button icon="delete" text type="primary"
                           v-show="scope.row.sjkssj === null || scope.row.sjkssj === ''"
                           @click="handleCancel(scope.row.coreId)">取消预约</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="state.pagination" />
        </el-tab-pane>
      </div>
    </el-tabs>
    <CoreDialog @refresh="getAllList()" ref="coreDialogRef" />
    <ChangeSeatDialog ref="changeSeatDialogRef" @refresh="getAllList" />
  </div>
</template>

<script setup lang="ts" name="infusionCore">
import {getInfusionStatistics, getList, getSeat, infusionCoreCancel , InfusionCoreStatistics} from '/@/api/infusion/config';
import { BasicTableProps, useTable} from "/@/hooks/table";
import { useMessage, useMessageBox } from "/@/hooks/message";
import {useI18n} from "vue-i18n";

// 引入组件
const CountDown = defineAsyncComponent(() => import('./countdown.vue'));
const CoreDialog = defineAsyncComponent(() => import('./form.vue'));
const ChangeSeatDialog = defineAsyncComponent(() => import('./changeSeat.vue'));

const activeName = ref('first');

const coreDialogRef = ref();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
const changeSeatDialogRef = ref();
const { t } = useI18n();

const otherState = reactive({
  seats: [] as RouteItems,
  toBeInfused: [] as RouteItems,
})
const statistics = reactive(<InfusionCoreStatistics>{
  totalInfusion: '',
  finishInfusion: '',
  totalInfusionBag: '',
  finishInfusionBag: '',
})

const state:BasicTableProps = reactive<BasicTableProps>({
  createdIsNeed: false,
  pageList: getList,
  queryForm: {
    infusionDate: '',
  }
});
const { getDataList, currentChangeHandle, sizeChangeHandle, tableStyle } = useTable(state);

onActivated(() => {
  init();
})

onMounted(() => {
  init();
});

// 清空搜索条件
const resetQuery = () => {
  queryRef.value.resetFields();
  init();
};

const init = function () {
  // 默认当前时间
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  state.queryForm.infusionDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + day;
  getAllList();
}

const getAllList = function() {
  // 获取列表模式
  getDataList();
  // 获取座位模式
  getSeatDataList();
  // 获取统计数据
  getStatistics();
}

const getStatistics = function () {
  const param = {
    infusionDate : state.queryForm.infusionDate
  }
  getInfusionStatistics(param).then((res) => {
    let data = res.data;
    statistics['totalInfusion'] = data['totalInfusion'];
    statistics['finishInfusion'] = data['finishInfusion'];
    statistics['totalInfusionBag'] = data['totalInfusionBag'];
    statistics['finishInfusionBag'] = data['finishInfusionBag'];
  });
}

const getSeatDataList = function () {
  const param = {
    infusionDate : state.queryForm.infusionDate
  }
  // 获取座位数据
  getSeat(param).then((res) => {
    let data = res.data;
    otherState.seats = data.seats;
    otherState.toBeInfused = data.toBeInfused;
  });
};

const onOpenCoreDialogRef = (type?: string, coreId?: string) => {
  coreDialogRef.value.openDialog(type, coreId);
};

const onOpenChangeSeatDialogRef = (data?: {type?:string, coreId?:string,seatId?:string }) => {
  if (data) {
    let type = data['type'];
    let coreId = data['coreId'];
    let seatId = data['seatId'];
    changeSeatDialogRef.value.openDialog(type,coreId, seatId);
  }
};

const checkDate = (date:string) => {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth() + 1;
  const day = today.getDate() < 10 ? '0' + today.getDate() : today.getDate();
  const todayFormat = year + '-' + (month < 10 ? '0' + month : month) + '-' + day;
  return todayFormat === date;
}

const checkEditDate = (date:string) => {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth() + 1;
  const day = today.getDate() < 10 ? '0' + today.getDate() : today.getDate();
  const todayFormat = year + '-' + (month < 10 ? '0' + month : month) + '-' + day;
  let date1 = new Date(todayFormat);
  let date2 = new Date(date);
  return date2 >= date1;
}

const tableRowClassName = (data?:{row:object, rowIndex:Number}) => {
  let row = data?.row;
  if (row['sjkssj']) {
    return row['sjjssj'] ? 'end-row': 'ing-row';
  }
  return '';
}

const handleCancel = async (coreId?:string) => {
  try {
    await useMessageBox().confirm(t('common.delConfirmText'));
  } catch(err) {
    console.log(err);
    return;
  }
  let param = {
    coreId : coreId,
  }
  try {
    await infusionCoreCancel(param);
    getAllList();
    useMessage().success(t('common.delSuccessText'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
}
</script>

<style>
.el-table .ing-row {
  background: #cffce6;
}

.el-table .end-row {
  background: #fccfcf;
}
</style>
